package com.hyh.eblog.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.code.kaptcha.Constants;
import com.hyh.eblog.common.lang.Result;
import com.hyh.eblog.dto.UserLoginParam;
import com.hyh.eblog.dto.UserRegisterParam;
import com.hyh.eblog.entity.Post;
import com.hyh.eblog.entity.User;
import com.hyh.eblog.entity.UserMessage;
import com.hyh.eblog.service.UserService;
import com.hyh.eblog.shiro.AccountProfile;
import com.hyh.eblog.util.UploadUtil;
import com.hyh.eblog.util.ValidationUtil;
import com.hyh.eblog.vo.CollectionVo;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Summerday
 * @since 2020-10-19
 */
@Controller
@RequestMapping("/user")
public class UserController extends BaseController {

    @Resource
    UserService userService;

    @Resource
    UploadUtil uploadUtil;

    @GetMapping("/login")
    public String login() {
        return "/auth/login";
    }

    @ResponseBody
    @PostMapping("/login")
    public Result doLogin(UserLoginParam loginParam) {
        ValidationUtil.ValidResult validResult = ValidationUtil.validateBean(loginParam);
        if (validResult.hasErrors()) {
            return Result.fail(validResult.getErrors());
        }
        Result result = userService.login(loginParam);
        return result.action("/index");
    }


    @GetMapping("/register")
    public String register() {
        return "/auth/reg";
    }

    @ResponseBody
    @PostMapping("/register")
    public Result doRegister(UserRegisterParam registerParam) {
        ValidationUtil.ValidResult validResult = ValidationUtil.validateBean(registerParam);
        if (validResult.hasErrors()) {
            return Result.fail(validResult.getErrors());
        }
        HttpSession session = request.getSession();
        String sessionText = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        session.removeAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (!sessionText.equalsIgnoreCase(registerParam.getCode())) {
            return Result.fail("验证码不正确");
        }
        if (!registerParam.getPassword().equals(registerParam.getRepass())) {
            return Result.fail("两次输入密码不相同");
        }
        Result result = userService.register(registerParam);

        return result.action("/user/login");
    }

    @GetMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "redirect:/";
    }

    @GetMapping("/home")
    public String home() {
        User user = userService.getById(getProfileId());
        // 30天内
        List<Post> posts = postService.list(new QueryWrapper<Post>()
                .eq("user_id", getProfileId())
                .gt("created", DateUtil.offsetDay(new Date(), -30))
                .orderByDesc("created")
        );
        request.setAttribute("user", user);
        request.setAttribute("posts", posts);
        return "/user/home";
    }

    @GetMapping("/set")
    public String set() {
        User user = userService.getById(getProfileId());
        request.setAttribute("user", user);
        return "/user/set";
    }

    @ResponseBody
    @PostMapping("/set")
    public Result doSet(User user) {
        if (StrUtil.isNotBlank(user.getAvatar())) {
            User temp = userService.getById(getProfileId());
            temp.setAvatar(user.getAvatar());
            userService.updateById(temp);
            AccountProfile profile = getProfile();
            profile.setAvatar(user.getAvatar());
            SecurityUtils.getSubject().getSession().setAttribute("profile",profile);
            return Result.success("上传成功").action("/user/set#info");

        }
        if (StrUtil.isBlank(user.getUsername())) return Result.fail("昵称不能为空");
        int count = userService.count(new QueryWrapper<User>()
                .eq("username", getProfile().getUsername())
                .ne("id", getProfileId()));
        if (count > 0) return Result.fail("该昵称已被占用");

        // 校验参数
        User temp = userService.getById(getProfileId());
        temp.setUsername(user.getUsername());
        temp.setCity(user.getCity());
        temp.setGender(user.getGender());
        temp.setSign(user.getSign().trim());
        userService.updateById(temp);
        AccountProfile profile = getProfile();
        profile.setUsername(temp.getUsername());
        profile.setAvatar(temp.getAvatar());
        profile.setSign(temp.getSign());
        SecurityUtils.getSubject().getSession().setAttribute("profile",profile);
        return Result.success("设置成功").action("/user/set#info");
    }

    @ResponseBody
    @PostMapping("/upload")
    public Result upload(@RequestParam(value = "file") MultipartFile file) throws IOException {
        return uploadUtil.upload(UploadUtil.type_avatar, file);
    }

    @ResponseBody
    @PostMapping("/repass")
    public Result repass(String nowpass, String pass, String repass) {
        if (StrUtil.isBlank(nowpass) || StrUtil.isBlank(pass) || StrUtil.isBlank(repass))
            return Result.fail("输入参数不能为空");
        if (!pass.equals(repass)) {
            return Result.fail("两次输入密码不一致");
        }
        User temp = userService.getById(getProfileId());
        if (!SecureUtil.md5(nowpass).equals(temp.getPassword())) {
            return Result.fail("当前密码输入错误");
        }
        temp.setPassword(SecureUtil.md5(pass));
        userService.updateById(temp);
        return Result.success("更改成功").action("/user/set#pass");
    }

    //@GetMapping("/message")
    //public String message() {
    //
    //    Page page = userMessageService.paging(getPage(), new QueryWrapper<UserMessage>()
    //            .eq("to_user_id", getProfileId())
    //            .orderByAsc("created"));
    //
    //    request.setAttribute("pageData",page);
    //    return "/user/message";
    //}

    @GetMapping("/index")
    public String index() {
        return "/user/index";
    }

    @ResponseBody
    @GetMapping("/collection")
    public Result collection() {
        IPage<CollectionVo> page = postService.paging(getPage(), getProfileId());
        return Result.success(page);
    }

    @ResponseBody
    @GetMapping("/public")
    public Result publish() {

        Page page = postService.page(getPage(), new QueryWrapper<Post>()
                .eq("user_id", getProfileId()).orderByDesc("created"));
        return Result.success(page);
    }
}
